package org.brownflat.watergate.scm.svn;

import org.brownflat.watergate.scm.Revision;
import org.brownflat.watergate.scm.RevisionBuilder;
import org.brownflat.watergate.scm.RevisionChange;
import org.springframework.stereotype.Component;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Component
public class SubversionRevisionBuilder implements RevisionBuilder<SVNLogEntry> {
    @Override
    public Revision build(SVNLogEntry entry) {
        SubversionRevision subversionRevision = new SubversionRevision();
        subversionRevision.setRevision(entry.getRevision());
        subversionRevision.setUser(entry.getAuthor());
        subversionRevision.setMessage(entry.getMessage());
        subversionRevision.setDate(entry.getDate());
        subversionRevision.setRevisionChanges(getRevisionChanges(entry));
        return subversionRevision;
    }

    private List<RevisionChange> getRevisionChanges(SVNLogEntry entry) {
        Map changedPaths = entry.getChangedPaths();
        List<RevisionChange> revisionChanges = new ArrayList<RevisionChange>();

        for(Object path : changedPaths.keySet()) {
            String filePath = (String) path;
            SVNLogEntryPath entryPath = (SVNLogEntryPath) changedPaths.get(filePath);

            SubversionRevisionChange revisionChange = new SubversionRevisionChange();
            revisionChange.setPath(filePath);
            revisionChange.setRevisionChangeType(entryPath.getType());
            revisionChange.setRevisionElementType(entryPath.getKind());
            revisionChanges.add(revisionChange);
        }

        return revisionChanges;
    }
}
